package com.creator.pangu.core.security.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.creator.pangu.base.entity.SysPermission;
import com.creator.pangu.base.entity.SysUser;
import com.creator.pangu.base.mapper.SysPermissionMapper;
import com.creator.pangu.base.mapper.SysUserMapper;
import com.creator.pangu.core.security.dto.LoginUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 处理登录业务逻辑
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysPermissionMapper sysPermissionMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StrUtil.isEmpty(username)) {
            throw new RuntimeException("用户名密码为空！");
        }
        // 查询用户信息
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", username).last("limit 1");
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        if (Objects.isNull(sysUser)) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        // 查询用户权限信息
        List<SysPermission> sysPermissionList = sysPermissionMapper.getSysPermissionListByUserId(sysUser.getUserId());

        return new LoginUser(sysUser, sysPermissionList);
    }


}
